import 'dart:math';

import 'package:app/components/TimeBox.dart';
import 'package:app/components/TimeView.dart';
import 'package:app/components/swiperView.dart';
import 'package:app/model/app_config.dart';
import 'package:app/model/model.dart';
import 'package:app/page/add.dart';
import 'package:app/page/countdownView.dart';
import 'package:app/router/router.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';

class PageA extends StatefulWidget {
  const PageA({super.key});
  @override
  State<PageA> createState() => _State();
}

class _State extends State<PageA> {
  final cList = CountdownEventClassList.create();
  final leftMenuIcon = TDIcons.menu_fold.obs;
  final viewIcon = TDIcons.view_list.obs;
  final titleStr = 'DAys Matter.倒数日'.obs;
  final selectedIndex = (-1).obs;

  var isView = false.obs;

  @override
  void initState() {

    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  void openDrawer(BuildContext ctx) {
    if (leftMenuIcon.value == TDIcons.menu_fold) {
      final drawerItems = [
        TDDrawerItem(title: "全部"),
        ...cList.countdownEventList.map(
          (item) => TDDrawerItem(title: item.name.value),
        ),
      ];

      TDDrawer(
        context,
        visible: true,
        placement: TDDrawerPlacement.left,
        drawerTop: MediaQuery.of(context).padding.top + 48,
        items: drawerItems,
        onClose: closeDrawer,
        onItemClick: (index, item) {
          if (index == 0 && item.title == "全部") {
            titleStr.value = 'DAys Matter.倒数日';
            selectedIndex.value = -1;
          } else {
            titleStr.value = 'DAys Matter.${item.title}';
            selectedIndex.value = index - 1;
          }
          Navigator.of(context).pop();
        },
      );

      leftMenuIcon.value = TDIcons.menu_unfold;
    }
  }

  void closeDrawer() {
    if (leftMenuIcon.value == TDIcons.menu_unfold) {
      leftMenuIcon.value = TDIcons.menu_fold;
    }
  }

  void toCountdownView(ChildrenEvent args) {
    context.routeOf<CountdownView>().arguments(args).to();
  }

  void swipeLeftDelete(
    BuildContext swipeLeftDeleteContext,
    ChildrenEvent event,
  ) {
    showGeneralDialog(
      context: swipeLeftDeleteContext,
      pageBuilder: (
        BuildContext buildContext,
        Animation<double> animation,
        Animation<double> secondaryAnimation,
      ) {
        return TDAlertDialog(
          content: '确定删除${event.name.value}吗？',
          rightBtnAction: () {
            var countdownEvent = cList.findCountdownEventClassById(
              event.parentId.value,
            );
            if (countdownEvent == null) {
              TDToast.showFail("参数错误", context: context);
              return;
            }
            countdownEvent.deleteEventChild(event.childrenId.value);
            Navigator.of(buildContext).pop();
          },
          leftBtnAction: () {
            Navigator.of(buildContext).pop();
          },
        );
      },
    );
  }

  void swipeLeftEdit(
    BuildContext swipeLeftEditContext,
    ChildrenEvent event,
  ) async {
    await swipeLeftEditContext.routeOf<Add>().arguments(event).to();
    isView.refresh();
  }

  void showActionSheet(
    BuildContext showActionSheetContext,
    ChildrenEvent event,
  ) {
    final List<TDActionSheetItem> items = [
      TDActionSheetItem(label: "编辑"),
      TDActionSheetItem(label: "删除", textStyle: TextStyle(color: Colors.red)),
    ];
    TDActionSheet.showListActionSheet(
      showActionSheetContext,
      items: items,
      onSelected: (_, index) {
        Future.delayed(const Duration(milliseconds: 0), () {
          if (index == 0) {
            swipeLeftEdit(showActionSheetContext, event);
            return;
          }
          swipeLeftDelete(showActionSheetContext, event);
        });
      },
    );
  }

  void cut() {
    if (isView.value) {
      isView.value = false;
      viewIcon.value = TDIcons.view_list;
      return;
    }
    isView.value = true;
    viewIcon.value = TDIcons.view_module;
  }

  Widget _buildEventList(BuildContext context) {
    return Obx(() {
      final eventChildren =
          selectedIndex.value == -1
              ? cList.countdownEventList
                  .expand((item) => item.eventChildren)
                  .toList()
              : cList.countdownEventList[selectedIndex.value].eventChildren;

      if (eventChildren.isEmpty) {
        return Expanded(
          flex: 7,
          child: Container(
            alignment: Alignment.center,
            child: _iconEmpty(context),
          ),
        );
      }

      return Expanded(
        flex: 7,
        child: Container(
          margin: EdgeInsets.only(top: 10),
          padding: EdgeInsets.symmetric(horizontal: 10),
          child: ListView.builder(
            itemCount:
                isView.value
                    ? (eventChildren.length / 2).ceil()
                    : eventChildren.length,
            itemBuilder: (context, index) {
              return Column(
                children: [
                  Obx(() {
                    if (isView.value) {
                      final firstEvent = eventChildren[index * 2];
                      final List<Widget> arr = [
                        TimeView(
                          childrenEvent: firstEvent,
                          isMin: true,
                          onTap: () {
                            toCountdownView(firstEvent);
                          },
                          onLongPress: () {
                            showActionSheet(context, firstEvent);
                          },
                        ),
                      ];
                      if (index * 2 + 1 < eventChildren.length) {
                        var s = [
                          TimeView(
                            childrenEvent: eventChildren[index * 2 + 1],
                            isMin: true,
                            onTap: () {
                              toCountdownView(eventChildren[index * 2 + 1]);
                            },
                            onLongPress: () {
                              showActionSheet(
                                context,
                                eventChildren[index * 2 + 1],
                              );
                            },
                          ),
                        ];
                        arr.addAll(s);
                      }
                      return GridView.count(
                        shrinkWrap: true,
                        physics: NeverScrollableScrollPhysics(),
                        crossAxisCount: 2,
                        mainAxisSpacing: 10,
                        crossAxisSpacing: 10,
                        childAspectRatio: 1.2,
                        children: arr,
                      );
                    }
                    final event = eventChildren[index];
                    return TimeBox(
                      name: event.name.value,
                      targetTimestamp: event.targetTimestamp.value,
                      color: event.eventColor.value,
                      children: [
                        TDSwipeCellAction(
                          flex: 20,
                          backgroundColor: Color(0xFFFA9550),
                          label: '编辑',
                          onPressed: (context) {
                            swipeLeftEdit(context, event);
                          },
                        ),
                        TDSwipeCellAction(
                          flex: 20,
                          backgroundColor: Color(0xFFD54941),
                          label: '删除',
                          onPressed: (context) {
                            swipeLeftDelete(context, event);
                          },
                        ),
                      ],
                      onTap: () {
                        toCountdownView(event);
                      },
                    );
                  }),
                  if (index < eventChildren.length - 1) SizedBox(height: 10),
                ],
              );
            },
          ),
        ),
      );
    });
  }

  Widget _buildSwiperView(BuildContext context) {
    return Obx(() {
      final allEvents =
          cList.countdownEventList
              .expand((item) => item.eventChildren)
              .toList();
      final topEventArr =
          allEvents.where((event) => event.whetherToTop.value).toList();

      if (topEventArr.isNotEmpty) {
        return Swiper(
          autoplay: topEventArr.length > 1,
          itemCount: topEventArr.length,
          loop: topEventArr.length > 1,
          pagination: const SwiperPagination(
            alignment: Alignment.bottomCenter,
            builder: TDSwiperPagination.dots,
          ),
          itemBuilder: (BuildContext context, int index) {
            return SwiperView(
              name: topEventArr[index].name.value,
              targetTimestamp: topEventArr[index].targetTimestamp.value,
            );
          },
        );
      }
      return SwiperView(name: "", targetTimestamp: 1);
    });
  }

  Widget _iconEmpty(BuildContext context) {
    return const TDEmpty(type: TDEmptyType.plain, emptyText: '事件为空');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TDNavBar(
        height: 48,
        titleWidget: Obx(() => Text(titleStr.value)),
        titleColor: Colors.white,
        centerTitle: false,
        backgroundColor: StaticAppConfig.appBarColor,
        titleFontWeight: FontWeight.w600,
        useDefaultBack: false,
        screenAdaptation: true,
        leftBarItems: [
          TDNavBarItem(
            iconWidget: Obx(
              () => Icon(leftMenuIcon.value, size: 24, color: Colors.white),
            ),
            action: () => openDrawer(context),
          ),
        ],
        rightBarItems: [
          TDNavBarItem(
            iconWidget: Obx(
              () => Icon(viewIcon.value, size: 24, color: Colors.white),
            ),
            action: cut,
          ),
          TDNavBarItem(
            icon: TDIcons.add,
            iconSize: 24,
            iconColor: Colors.white,
            action: () {
              context.routerTo(Add);
            },
          ),
        ],
      ),
      body: GestureDetector(
        onTap: () => TimeBox.close(),
        child: Container(
          alignment: Alignment.center,
          decoration: BoxDecoration(color: Color(0xFFCCCCCC)),
          child: Column(
            children: [
              Expanded(child: _buildSwiperView(context)),
              _buildEventList(context),
            ],
          ),
        ),
      ),
    );
  }
}
